package biz.yfsoft.app.fastframework.core;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import biz.yfsoft.app.fastframework.Constant;
import biz.yfsoft.app.fastframework.bo.Bo;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;


public class BaseFastController extends Controller {
	
	public boolean invokeResult = true;
	
	public String failReason = "";
	
	protected void fail(String reason){
		invokeResult = false;
		failReason = reason;
		this.setAttr("error", failReason);
	}
	
	protected Map<String,Object> prevAdd(Map<String,Object> args) {
		return args;
	}
	
	public void logSession(Record user){
		
	}
	
	//将配置信息加入到配置中
	public boolean setConfig(String key,Object val){
		if(hasConfig(key)){
			//modify
			Record r = Db.findFirst("select * from sys_setting where name = ? and status > 0", key);
			r.set("val", val);
			r.set(Bo.UPDATE_TIME, System.currentTimeMillis());
			return Db.update("sys_setting", r);
		}else{
			//create 
			Bo bo = new Bo();
			bo.set("name",key);
			bo.set("title",key);
			bo.set("category","UDF");
			bo.set("val",val);
			bo.create();
			return Db.save("sys_setting", bo);
		}
	}
	
	public Record getCurrentUser(){
		Subject currentUser = SecurityUtils.getSubject();
		Session ss = currentUser.getSession();
		return (Record)ss.getAttribute(Constant.CURRENT_USER);
	}
	
	/**
	 * 从配置集中获取配置信息
	 * @param key
	 * @return
	 */
	public String getConfig(String key,String defVal){
		//先获取配置文件下的配置信息
		PropKit.use("config.txt");
		String val = PropKit.get(key);
		if(StrKit.notBlank(val)){
			return val;
		}
		Record r = Db.findFirst("select * from sys_setting where name = ? and status > 0", key);
		if(r==null){
			return defVal;
		}
		return r.get("val");
	}
	
	/**
	 * 是否包含某个配置
	 * @param key
	 * @return
	 */
	public boolean hasConfig(String key){
		PropKit.use("config.txt");
		if(PropKit.containsKey(key)){
			return true;
		}
		Long i = Db.queryLong("select count(*) as i from sys_setting where name = ? and status > 0", key);
		return i>0;
	}
	
	/**
	 * 获取url中的参数
	 * @param key 参数名
	 * @return
	 */
	public String i(String key){
		return getPara(key);
	}

	/**
	 * 获取url参数中的数据格式化成Map的方式
	 * 
	 * @return
	 */
	public Map<String, Object> getParams() {
		Map<String, Object> map = new HashMap<String,Object>();
		for(Enumeration<String> names = super.getParaNames();names.hasMoreElements();){
			String name = names.nextElement();
			map.put(name, getPara(name));
		}
		return map;
	}
	
	public Map<String, String> getStringParams() {
		Map<String, String> map = new HashMap<String,String>();
		for(Enumeration<String> names = super.getParaNames();names.hasMoreElements();){
			String name = names.nextElement();
			map.put(name, getPara(name));
		}
		return map;
	}
	
	public Map<String,String> getDecodeParams(String charset){
		Map<String, String> map = new HashMap<String,String>();
		for(Enumeration<String> names = super.getParaNames();names.hasMoreElements();){
			String name = names.nextElement();
			String val = getPara(name);
			if(StrKit.notBlank(val)){
				try {
					val = URLDecoder.decode(val, charset);
				} catch (UnsupportedEncodingException e) {
				}
			}
			map.put(name, val);
		}
		return map;
	}
	/**
	 * 开关插件
	 * @param p 插件的标示名称
	 * @return true:关闭,false：开启
	 */
	public boolean togglePlugin(String p){
		String config = getConfig("PluginActived","[]");
		JSONArray ja = JSONArray.parseArray(config);
		boolean f = ja.contains(p);
		if(f){
			//remove
			ja.remove(p);
		}else{
			ja.add(p);
		}
		setConfig("PluginActived",ja.toJSONString());
		return  f;
	}
	
	/**
	 * 开关插件
	 */
	public void togglePlugin(){
		String p = this.getPara(0);
		renderJson(wrapJson(0,null,togglePlugin(p)));
	}
	
	/**
	 * 通过传递相应的参数进行json格式数据的封装
	 * @param code 操作码：通常为 0 表示正常， >0 表示特定返回值， <0 表示错误 
	 * @param msg 出现错误时，该值会纪录错误信息
	 * @param data 操作成功之后会携带必要的数据
	 * @param rows 存放数据集合，为数组类型
	 * @return
	 */
	public String wrapJson(int code,String msg,Object data,List<?> rows){
		JSONObject jo = new JSONObject();
		jo.put("code", code);
		if(StrKit.notBlank(msg))
			jo.put("msg",msg);
		if(null!=data)
			jo.put("data",data);
		if(null!=rows)
			jo.put("rows",rows);
		return jo.toJSONString();
	}
	
	public String wrapJson(int code,String msg,Object data){
		return wrapJson(code,msg,data,null);
	}
	
	public String wrapJson(int code,String msg){
		return wrapJson(code,msg,null,null);
	}
	
	public String wrapJson(int code){
		return wrapJson(code,"",null,null);
	}
	
	/**
	 * 判断是否GET请求方式
	 * @return
	 */
	protected boolean isGet(){
		return (getRequest().getMethod().equalsIgnoreCase("GET"));
	}
	
	/**
	 * 判断是否POST请求方式
	 * @return
	 */
	protected boolean isPost(){
		return (getRequest().getMethod().equalsIgnoreCase("POST"));
	}
}
